package org.linlinjava.litemall.admin.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.admin.annotation.LoginAdmin;
import org.linlinjava.litemall.admin.constant.PermType;
import org.linlinjava.litemall.admin.util.StatVo;
import org.linlinjava.litemall.admin.vo.Json;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.SysPerm;
import org.linlinjava.litemall.db.domain.SysRole;
import org.linlinjava.litemall.db.service.LitemallRolePermService;
import org.linlinjava.litemall.db.service.LitemallRoleService;
import org.linlinjava.litemall.db.service.LitemallSysPermService;
import org.linlinjava.litemall.db.service.LitemallUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色管理
 *
 * @author zhy
 * @create 2018-09-28 11:27
 **/
@RestController
@RequestMapping("/admin/role")
public class RoleController {
	private final Log logger = LogFactory.getLog(RoleController.class);

	@Autowired
	private LitemallRoleService litemallRoleService;

	@Autowired
	private LitemallUserRoleService litemallUserRoleService;

	@Autowired
	private LitemallSysPermService litemallSysPermService;

	@Autowired
	private LitemallRolePermService litemallRolePermService;

	@PostMapping("/deleteRole")
	public Object delete(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		litemallRoleService.deleteById(sysRoles);
		return ResponseUtil.ok();
	}
	@PostMapping("/addRole")
     public Object create(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
        String rname=sysRoles.getRname();
		rname = rname.replaceAll(" ", "");
		sysRoles.setRname(rname);
		List<SysRole> sysRoles1=litemallRoleService.queryByRname(rname);
		if(sysRoles1.size() > 0){
			return ResponseUtil.fail(403, "角色名已注册");
		}
        sysRoles.setCreated(LocalDateTime.now());
		litemallRoleService.addRole(sysRoles);
		return ResponseUtil.ok(sysRoles);
	}
    @PostMapping("/updateUserRole")
    public Object updateUserRole(@LoginAdmin Integer adminId,@ RequestBody String body){
	    if (adminId == null) {
		    return ResponseUtil.unlogin();
	    }
	    JSONObject json = JSON.parseObject(body);
	    final String uid = json.getString("user_id");
	    List<String> rids = json.getJSONArray("role_id").toJavaList(String.class);
	    Integer iuid = Integer.valueOf(uid);

	    //删除：原来绑定的角色
	    litemallUserRoleService.deleteUserRole(iuid);

	    //更新：绑定新的角色
	    for (int i=0;i<rids.size();i++){
		    String roleid=rids.get(i);
		    Integer iroleid=Integer.valueOf(roleid);
		    litemallUserRoleService.addValue(iuid,iroleid);
	    }

        return ResponseUtil.ok();
    }
    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId,@RequestBody SysRole sysRoles ){
	    if (adminId == null) {
		    return ResponseUtil.unlogin();
	    }
	    String rname=sysRoles.getRname();
	    rname = rname.replaceAll(" ", "");
	    sysRoles.setRname(rname);
	    List<SysRole> sysRoles1=litemallRoleService.queryByRname(rname);
	    if(sysRoles1.size() > 0){
		    return ResponseUtil.fail(403, "角色名已注册");
	    }
	    sysRoles.setUpdated(LocalDateTime.now());
	    litemallRoleService.updateRole(sysRoles);
	    return ResponseUtil.ok(sysRoles);
    }

	@GetMapping("/query")
	public Object list(@LoginAdmin Integer adminId,
		String rname,
		@RequestParam(value = "page", defaultValue = "1") Integer page,
		@RequestParam(value = "limit", defaultValue = "10") Integer limit,
		String sort, String order) {
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
        List<SysRole> sysRoles = litemallRoleService.queryAll(rname,page,limit,sort,order);
		long total = PageInfo.of(sysRoles).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", sysRoles);

		return ResponseUtil.ok(data);
	}

	@GetMapping("getAllRole")
	public Object lists(@LoginAdmin Integer adminId){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}
		List<SysRole> sysRoles = litemallRoleService.queryAll2();
		Map<String, Object> data = new HashMap<>();
		data.put("items", sysRoles);
		return ResponseUtil.ok(data);
	}

	@GetMapping("getRoleByUser")
	public Object rolebyuser(@LoginAdmin Integer adminId,String id){
		if (adminId == null) {
			return ResponseUtil.unlogin();
		}

		List<Map> rows = litemallRoleService.getUserRole(id);
		StatVo statVo = new StatVo();
		statVo.setRows(rows);

		return ResponseUtil.ok(statVo);
	}

	@GetMapping("/{rid}/perms")
	public Object findRolePerms(@PathVariable String rid){
		String oper = "find role perms";
		if (StringUtils.isBlank(rid)){
			return Json.fail(oper, "无法查询当前角色的权限值：参数为空（角色id）");
		}
		Integer rids = Integer.valueOf(rid);
		SysRole role = litemallRoleService.selectById(rids);
		List<SysPerm> perms = litemallSysPermService.getPermsByRoleId(rids);
		Map<Integer, List<SysPerm>> permMap = perms.stream().collect(Collectors.groupingBy(SysPerm::getPtype));

		List<String> menuPvals = permMap.getOrDefault(PermType.MENU, new ArrayList<>()).stream()
			.filter(perm->perm.getLeaf()==true).map(SysPerm::getPval).collect(Collectors.toList());

		Map<String, Object> data = new HashMap<>();
		data.put("role" ,role);
		data.put("menuPvals", menuPvals);
		return ResponseUtil.ok(data);
	}

	@PostMapping("/perm")
	public Object updateRolePerm(@RequestBody String  body) {

		String oper = "update role's permissions";

		JSONObject json = JSON.parseObject(body);
		final Integer ptype = json.getInteger("ptype");
		final Integer rid = json.getInteger("rid");
		List<String> pvals = json.getJSONArray("pvals").toJavaList(String.class);
		if(pvals.size()==0){
			return ResponseUtil.ok();
		}else{
			// 删除相应的数据
			litemallRolePermService.deleteByidPtype(rid,ptype);

			// 插入数据
			for(int i=0;i<pvals.size();i++){
                String pval = pvals.get(i);
                litemallRolePermService.insertOne(rid,pval,ptype);
			}
			return ResponseUtil.ok();
	}
	}

    @PostMapping("/permsss")
    public Json addPerm(@RequestBody String body){
        String oper="add role's permissions";
	    JSONObject json = JSON.parseObject(body);
	    String rid = json.getString("rid");
	    Integer rids = Integer.valueOf(rid);
	    Integer ptype = json.getInteger("ptype");
	    String pval = json.getString("pval");

//	    SysRolePerm sysRolePerm = new SysRolePerm();
//	    sysRolePerm.setRoleId(rids);
//	    sysRolePerm.setPermType(ptype);
//	    sysRolePerm.setPermVal(pval);
//	    litemallRolePermService.insertRolePerm(sysRolePerm);
	    return Json.result(oper,true);
    }

	@DeleteMapping("/perm")
	public Json deletePerm(@RequestBody String body){
		String oper = "delete role's permissions";

		JSONObject json = JSON.parseObject(body);
		String rid = json.getString("rid");
		Integer rids = Integer.valueOf(rid);
		Integer ptype = json.getInteger("ptype");
		String pval = json.getString("pval");

		litemallRolePermService.deleteOne(rids,ptype,pval);
		return Json.succ(oper,true);
	}
}


